<?php
namespace app\wechat\model;
use think\Model;
use EasyWeChat\Factory;

use app\user\model\WechatReply;
use app\user\model\WechatNews;

class WechatTemplate extends Model
{
    protected $json = ['jdata'];
    protected $jsonAssoc = true;

    protected $autoWriteTimestamp = true;

    protected $globalScope = ['store_id'];
    public function scopeStore_id($query)
    {
        $query->where('store_id', StoreId());
    }

    public function task()
    {
        return $this->hasMany(WechatTemplateTask::class,'tid','id')->where('status',0);
    }
    //获取菜单消息
    public static function update_template()
    {
        $wxapp = wxapi(StoreId(),'weixin');
        $data = $wxapp->template_message->getPrivateTemplates();
        foreach ($data['template_list'] as $r){
            $temp = self::where('template_id',$r['template_id'])->find();
            if(empty($temp)){
                $r['store_id'] = StoreId();
                self::create($r);
            }
        }
        return;
    }

    /**
     * 发送模板消息
     * @param $data
     * @param $openid
     * @param $id
     */
    public static function send_template($data,$openid,$id)
    {
        $wxapp = wxapi(StoreId(),'weixin');
        $result = $wxapp->template_message->send([
            'touser' => $openid,//'ouHWJjsWMrjETR0CdC2sPxfvYxac',//
            'template_id' => $data['template_id'],
            'url' => $data['url'],
            'miniprogram' => [
                'appid' => $data['appid'],
                'pagepath' => $data['pagepath'],
            ],
            'data' => $data['jdata'],
        ]);
        WechatTemplateTask::where('id',$id)->update(['status'=>1,'error'=>$result['errmsg']]);
    }
    
}